﻿using Microsoft.Ink;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfControlDemo.InkCanvas
{
    /// <summary>
    /// 手写识别文字看板
    /// </summary>
    public partial class RecognizeWindow : Window
    {
        public RecognizeWindow()
        {
            InitializeComponent();
        }

        Ink ink = new Ink();
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // 文字识别对象
            using RecognizerContext recognizerContext = new RecognizerContext();
            #region 第一步-转换笔记轨迹点集合
            // 实例化Strokes对象-需要注意ink与转换的ink要是同一个对象
            recognizerContext.Strokes = ink.CreateStrokes();
            // 添加转换后的轨迹点集合数据
            recognizerContext.Strokes.Add(CombineStroke());
            #endregion

            #region 第二步识别笔记
            // 识别轨迹 - RecognitionStatus status（识别的状态） result（识别的结果）
            RecognitionResult result = recognizerContext.Recognize(out RecognitionStatus status);
            // 获取返回的识别结果可选项-
            RecognitionAlternates als = result.GetAlternatesFromSelection();
            // 循环遍历显示识别出来的可选项
            List<string> strs = new List<string>();
            StringBuilder str= new StringBuilder();
            for (int i = 0; i < als.Count; i++)
            {
                strs.Add(als[i].ToString());
                str.Append($"{als[i].ToString()}、");
            }
            tbText.Text= str.ToString();
            #endregion
        }

        /// <summary>
        /// 将Canvas看板的Stroke转换成文字识别对象的Stroke
        /// </summary>
        /// <returns></returns>
        private Stroke CombineStroke()
        {
            // 上下文的笔记点集合
            List<System.Drawing.Point> points = new List<System.Drawing.Point>();
            // 循环看板的Strokes所有的线
            foreach (var item in this.inkCanvas.Strokes)
            {
                // 将看板的轨迹点类型转换成上下文的轨迹点类型并添加到上下文的点集合中。
                points.AddRange(
                    item.StylusPoints.Select(p => new System.Drawing.Point((int)p.X, (int)p.Y)).ToList()
                );
            }
            // 创建成识别对象可以使用的Stroke
            Stroke stroke = ink.CreateStroke(points.ToArray());
            // 返回
            return stroke;
        }
    }
}
